//
//  PhotoBrowserViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/7/5.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

private let reuseIdentifier = "CCLargePhotoCell"

class PhotoBrowserViewController: UIViewController{
    
    /**
    关闭当前控制器
    */
    func close(){
        dismissViewControllerAnimated(true, completion:nil)
    }
    func save(){
        let image = currentImageView().image!
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    func currentImageIndex() -> Int{
        return collectionView.indexPathsForVisibleItems().last!.item
    }
    func currentImageView() -> UIImageView {
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as!
        PhotoViewCell
        
        return cell.imageView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print(imageURLs)
    
    }
    func image(image :UIImage, didFinishSavingWithError error:NSError?, contextInfo :AnyObject) {
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        prepareLayout()
        
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    private func prepareLayout(){
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    override func loadView() {
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        
        view = UIView(frame: screenBounds)
        view.backgroundColor = UIColor.blackColor()
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectionView()
    }
    private func prepareCollectionView(){
        //collectionView.backgroundView = UIColor.clearColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(PhotoViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    init(urls:[NSURL],index:Int){
        imageURLs = urls
        currentIndex = index
        
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private var imageURLs:[NSURL]
    private var currentIndex:Int

   // MARK: - 控件懒加载
    private lazy var layout = UICollectionViewFlowLayout()
    lazy private var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    private lazy var saveButton:UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.tintColor = UIColor.purpleColor()
        btn.backgroundColor = UIColor.greenColor()
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        return btn
    }()
    private lazy var closeButton:UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.tintColor = UIColor.purpleColor()
        btn.backgroundColor = UIColor.greenColor()
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        return btn
        }()
    private var photoScale: CGFloat = 0
}

extension PhotoBrowserViewController :UICollectionViewDataSource,UICollectionViewDelegate,PhotoViewCellDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoViewCell
        
        cell.backgroundColor = UIColor.clearColor()
        cell.imageURL = imageURLs[indexPath.item]
        
        cell.photoDelegate = self
        return cell
    }
    
    
    func photoViewCellDidTapImage() {
        close()
    }
    
    func photoViewerDidZooming(scale:CGFloat){
        photoScale = scale
        hideControl(photoScale<1.0)
        
        if photoScale < 1.0{
            startInteractiveTransition(self)
        }else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
    func photoViewerDidEndZoom() {
        if photoScale < 0.8 {
            completeTransition(true)
        }
    }
    ///  隐藏控件
    private func hideControl(isHidden: Bool) {
        view.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        saveButton.hidden = isHidden
        closeButton.hidden = isHidden
    }
}

extension PhotoBrowserViewController: UIViewControllerInteractiveTransitioning, UIViewControllerContextTransitioning {
    
    ///  transitionContext 是提供专场所需的所有信息
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 缩放视图
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        // 设置透明度
        view.alpha = photoScale
    }
    
    ///  转场动画中，这个函数很重要，告诉转场动画结束
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? { return self.view.superview }
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return true }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    func viewForKey(key: String) -> UIView? { return self.view }
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}